package com.study.poolftp;

import cn.hutool.extra.ftp.Ftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.io.IOException;
import java.util.Objects;

/**
 * @author zhuzi
 * 2022/8/28 09:47
 * <a href="https://juejin.cn/post/6844903728747642893">springboot FTP对象池</a>
 *
 * <a href="https://blog.csdn.net/chengmin123456789/article/details/113864940">使用</a>
 */
@Slf4j
public class FtpClientFactory extends BasePooledObjectFactory<Ftp> {
    private FtpClientProperties config;

    public FtpClientFactory(FtpClientProperties properties) {
        this.config = properties;
    }

    /**
     * 创建对象
     */
    @Override
    public Ftp create() throws Exception {
        Ftp ftp = new Ftp(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());
        log.info("对象池--创建FTP [{}]", ftp);
        return ftp;
    }

    @Override
    public PooledObject<Ftp> wrap(Ftp obj) {
        return new DefaultPooledObject<>(obj);
    }

    /**
     * 销毁
     */
    @Override
    public void destroyObject(PooledObject<Ftp> p) throws Exception {
        Ftp ftp = p.getObject();
        if (Objects.isNull(ftp)) {
            return;
        }
        try {
            log.info("对象池-销毁对象");
            ftp.close();
        } catch (IOException e) {
            log.error("对象池-关闭异常", e);
        }
    }

    /**
     * 验证FTPClient对象
     *
     * @return
     */
    @Override
    public boolean validateObject(PooledObject<Ftp> p) {
        Ftp ftp = getObject(p);
        if (Objects.isNull(p)) {
            return false;
        }
        try {
            return ftp.getClient().sendNoOp();
        } catch (IOException e) {
            return false;
        }
    }

    private Ftp getObject(PooledObject<Ftp> pooledObject) {
        if (Objects.isNull(pooledObject) && Objects.isNull(pooledObject.getObject())) {
            return null;
        }
        return pooledObject.getObject();
    }
}
